import React, {Component} from 'react';
import {AsyncStorage, DeviceEventEmitter, Image, ListView, ScrollView, View,} from 'react-native';
import Navigation from "../custom/Navigation";
import HomePage from '../pages/HomePage';
import CategoryPage from '../pages/category/CategoryPage';
import MePage from '../pages/mePage/MePage';
import SideMenu from 'react-native-side-menu';
import Menu from './Menu';
import StyleUtils from "../res/styles/StyleUtils";
import LoginPage from "../pages/common/LoginPage";
import CommonUtils from "../common/CommonUtils";
import SettingsPage from "../pages/mePage/SettingsPage";
import ScrollArticle from "../pages/article/ScrollArticle";
import ShopPage from "../pages/shopPage/ShopPage";
import OrdersPage from "../pages/mePage/order/OrdersPage";
import SelectCountryPage from "../pages/common/SelectCountryPage";
import ModalListUtils from "../utils/ModalListUtils";
import I18n from "../res/language/i18n";
import IparNetwork, {SERVER_TYPE} from "../httpUtils/IparNetwork";
import BarcodeTest from "../utils/BarcodeTest";
import AdvertisementModal from "../utils/AdvertisementModal";
import UserInformation from "../pages/mePage/userInfo/UserInformation";
import AboutAppPage from "../pages/AboutAppPage";
import SubAccountsPage from "../pages/mePage/business/SubAccountsPage";
import AlertDialog from "../custom/AlertDialog";
import BusinessPlanPage from "../pages/mePage/business/BusinessPlanPage";
import MessageListPage from "../pages/common/MessageListPage";


import TabNavigator from 'react-native-tab-navigator';
import ArticlePageNew from "../pages/article/ArticlePageNew";
import ProductAdvertising from "../utils/ProductAdvertising";
import MandatoryProductPage from "../pages/common/MandatoryProductPage";
import SearchView from "../custom/SearchView";
import UPush from "react-native-upush";

const pageTitles = ['HomePage', 'CategoryPage', 'ScrollArticle', 'ShopPage', 'MePage'];

export const menuClickTypes = {
    userAvatar: 'user-avatar',
    message: 'message',
    business: 'My business',
    orders: 'My orders',
    country: 'Country',
    language: 'Language',
    // business: 'Start business',
    // agreement: 'Service agreement',
    // customer: 'Customer service',
    about: 'about',

};


let languageData = [
    {name: I18n.t('default.english'), code: 'en'},
    {name: I18n.t('default.russian'), code: 'ru'},
    {name: I18n.t('default.chines'), code: 'zh'},
    // {name: I18n.t('default.uyghur'), code: 'uy'},
];


export default class SlideMenu extends Component {


    constructor(props) {
        super(props);

        let ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2,
        });

        this.iparNetwork = new IparNetwork();
        this.state = {
            isOpen: false,
            productAdvertisingVisible: false,
            recommendAlertVisible: false,
            visibleSearch: false,
            userData: null,
            shopCardLength: 0,
            messageNum: 0,
            languageVisible: false,
            languageData: ds.cloneWithRows(languageData),

            advertisementModalVisible: false,
            advertisementModalData: null,
            isRemoveToolbarIcon: false,
            selectedTab: pageTitles[0],
        };
    }


    componentWillUnmount() {
        this.iparNetwork = null;
        this.deEmitter && this.deEmitter.remove();
        this.deEmitterUserData && this.deEmitterUserData.remove();
        // this.deEmitterGoto && this.deEmitterGoto.remove();
        this.alertTimer && clearTimeout(this.alertTimer)

    }

    componentDidMount() {

        //请选择语言
        let props = this.props;
        if (props.isFirst) {
            this.setState({
                languageVisible: true,
            });
        }


        //获取用户头像&&是否登陆
        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                if (result) {
                    let resultData = JSON.parse(result);
                    this.setState({
                        userData: resultData,
                    });


                    this.getUserInfo(resultData.user_id);


                    /**
                     * 购物车数量
                     */
                    this.getShopCardLength();
                    this.deEmitter = DeviceEventEmitter.addListener('isBuyGoods', () => {
                        this.getShopCardLength();
                    });


                    /**
                     * 改成子账号。。
                     */
                    this.deEmitterUserData = DeviceEventEmitter.addListener('upDateUserData', (userData) => {
                        if (!userData) return;
                        CommonUtils.saveUserInfo(userData);
                        if (userData && userData !== this.state.userData) {
                            if (this.state.userData.user_id != userData.user_id) {
                                this.getShopCardLength(userData.user_id);
                                this.getSysVoucher();
                            }
                        }
                        this.setState({
                            userData: userData,
                        });
                    });

                    //获取信息的数量
                    this.getMessageNum(resultData.main_user_id);
                }
            }).catch((error) => {
        });


        /**
         * 优惠券
         */
        if (props.isFirst !== true) {
            this.getSysVoucher();
        }


        this.deEmitterGoto = DeviceEventEmitter.addListener('goToPage', (index) => {
            if (this.state.selectedTab !== pageTitles[index]) {
                this.setState({
                    selectedTab: pageTitles[index]
                })
            }
        });


        if (props.startPage) {
            props.navigator.push({
                component: props.startPage.component,
                params: props.startPage.params,
            })
        }




        // UPush.onOpenListener((msg) => {
        //
        //     if (!msg) return;
        //     if (!msg.body) return;
        //
        //
        //     const {navigator} = this.props;
        //     let types = msg.body.types;
        //     if (types.indexOf("order") !== -1) {
        //         navigator.push({
        //             component: OrdersPage,
        //             name: 'OrdersPage',
        //         });
        //     } else if (types.indexOf("user")) {
        //         DeviceEventEmitter.emit('goToPage', 4)
        //     }
        //
        //     console.log("upush---onOpenListener: ", msg);
        // });

    }

    /**
     * 推荐用户升级
     */
    startActivatedAlert() {

        let date = new Date();
        let _date = date.getDate();

        /**
         * 每天更新
         */
        AsyncStorage.getItem('openDay', (error, result) => {
            if (result !== _date + "") {
                AsyncStorage.setItem('openDay', _date + "",);
                this.setState({
                    recommendAlertVisible: true,
                });
            }
        });
    }


    /**
     * 获取用户详细信息
     */
    getUserInfo(user_id) {
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getSubAccount?', 'user_id=' + user_id)
            .then((result) => {
                this.setState({showLoading: false});
                if (result.code === 200) {
                    let userData = result.data;
                    CommonUtils.saveUserInfo(userData);
                    this.setState({
                        userData: userData,
                    });

                    /**
                     * 推荐用户升级
                     */
                    if (userData.open_plan_num <= 1) {
                        this.startActivatedAlert();
                    }
                }
            })
            .catch((error) => {
                console.log(error)
            })
    }

    /**
     * 获取信息的数量
     */
    getMessageNum(mainUserId) {
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getMessageStatistics?', 'receiver_main_user_id=' + mainUserId)
            .then((result) => {
                if (result.data) {
                    this.setState({
                        messageNum: result.data.unread_num
                    })
                }
            });
    }


    /**
     * 获取优惠券
     */
    getSysVoucher() {
        CommonUtils.getAcyncInfo('country_iso')
            .then((result) => {
                this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getSysVoucher?',
                    'country=' + result)
                    .then((result) => {
                        if (result.code === 200) {
                            this.timer = setTimeout(() => {
                                this.setState({
                                    advertisementModalData: result.data,
                                    advertisementModalVisible: true,
                                });
                                this.timer && clearTimeout(this.timer)
                            }, 6000);
                        }
                    })
                    .catch((error) => {
                        console.log('SlideMenu--componentDidMount----优惠券-error: ', error);
                    })
            })
    }


    /**
     * 获取购物车数量
     */
    getShopCardLength(user_id) {
        let userId = user_id ? user_id : this.state.userData.user_id;
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getCartNum?', 'user_id=' + userId)
            .then((result) => {

                let _num;
                if (result.code === 200 && result.data > 0) {
                    _num = result.data;
                }
                this.setState({
                    shopCardLength: _num,
                });

            })
            .catch((error) => {
                console.log('SlideMenu--getShopCardLength--error-', error)
            })
    }

    /**
     * 手该语言
     */
    editLanguage(code) {
        this.setState({
            languageVisible: false,
        });
        I18n.locale = code;
        AsyncStorage.setItem('lang', code, (error, result) => {

        })
    }

    /**
     * 点击left menu items
     * @param item
     */
    onMenuItemSelected(item) {
        this.setState({
            isOpen: false
        });


        let _component = null;
        let _params = {...this.props};
        let login = this.state.userData;
        let userData = this.state.userData;
        switch (item) {
            case menuClickTypes.userAvatar:
                _component = login ? UserInformation : LoginPage;
                _params = login ? {userInfo: userData} : {};
                break;
            case menuClickTypes.business:
                if (login) {
                    _component = userData.open_plan_num <= 1 ? BusinessPlanPage : SubAccountsPage;
                    _params = {userId: userData ? userData.main_user_id : ''};
                } else {
                    _component = LoginPage;
                }

                break;
            case menuClickTypes.orders:
                _component = login ? OrdersPage : LoginPage;
                break;
            case menuClickTypes.country:
                _component = login ? SettingsPage : SelectCountryPage;
                break;
            case menuClickTypes.language:
                this.setState({
                    languageVisible: true,
                });
                break;
            // case menuClickTypes.business:
            // 	_component = login ? MyBusinessPage : LoginPage;
            // 	break;
            // case menuClickTypes.agreement:
            // 	_component = ArtcleListPage;
            // 	_params = {cateId: 18};
            // 	break;
            // case menuClickTypes.customer:
            // 	_component = CustomerServicePage;
            // 	break;
            case menuClickTypes.about:
                _component = AboutAppPage;
                break;
            case menuClickTypes.message:
                _component = login ? MessageListPage : LoginPage;
                _params = login ? {
                    callback: (newMessageNum) => {
                        if (this.state.messageNum !== newMessageNum) {
                            this.setState({messageNum: newMessageNum})
                        }
                    }
                } : {};
                break;
        }

        if (_component) {
            this.props.navigator.push({
                component: _component,
                name: _component + '',
                params: _params || {}
            })
        }
    }


    /**
     * init tan navigator
     * */
    getTabNavigator(title, icon, Component, params, badgeText) {
        return <TabNavigator.Item
            badgeText={badgeText}
            selected={this.state.selectedTab === title}
            renderIcon={() => <Image style={StyleUtils.tabIconSize} source={icon}/>}
            onPress={() => {
                if ((title === pageTitles[3] || title === pageTitles[4]) && !this.state.userData) {
                    this.props.navigator.push({
                        component: LoginPage,
                        name: 'LoginPage',
                    });
                } else {
                    this.setState({selectedTab: title})
                }
            }}>
            <Component {...params} {...this.props}/>
        </TabNavigator.Item>

    }


    render() {


        let state = this.state;
        const menu = <Menu
            messageNum={state.messageNum}
            userData={state.userData}
            onItemSelected={(item) => this.onMenuItemSelected(item)}/>;

        return (
            <SideMenu
                menu={menu}
                isOpen={state.isOpen}
                onChange={isOpen => this.setState({isOpen})}
            >
                <View style={StyleUtils.flex}>
                    <Navigation
                        onClickLeftBtn={() => this.setState({
                            isOpen: !state.isOpen,
                        })}
                        onClickRightBtn={() => {
                            this.props.navigator.push({
                                component: BarcodeTest,
                                name: 'BarcodeTest',
                                params: {
                                    userData: this.state.userData,
                                }
                            })
                        }}
                        onClickRightBtnTow={() => {
                            this.setState({
                                visibleSearch: true,
                            });
                        }}
                        leftButtonIcon={require('../res/images/ic_menu.png')}
                        rightButtonIcon={require('../res/images/ic_qr_code.png')}
                        rightButtonIconTow={require('../res/images/ic_search.png')}
                        titleImage={require('../res/images/ic_ipar_logo.png')}
                    />

                    <TabNavigator tabBarStyle={{backgroundColor: 'white'}}>
                        {this.getTabNavigator(pageTitles[0], require('../res/images/tabIcons/ic_home.png'), HomePage, {userInfo: state.userData})}
                        {this.getTabNavigator(pageTitles[1], require('../res/images/tabIcons/ic_category.png'), CategoryPage,)}
                        {this.getTabNavigator(pageTitles[2], require('../res/images/tabIcons/ic_ipar.png'), ArticlePageNew,)}
                        {this.getTabNavigator(pageTitles[3], require('../res/images/tabIcons/ic_shop.png'), ShopPage, {userData: state.userData}, this.state.shopCardLength)}
                        {this.getTabNavigator(pageTitles[4], require('../res/images/tabIcons/ic_me.png'), MePage, {userInfo: state.userData})}
                    </TabNavigator>

                    {/**语言*/}
                    {state.languageVisible ? <ModalListUtils
                        close={() => {
                            this.setState({
                                languageVisible: false
                            })
                        }}
                        title={I18n.t('default.selectLanguage')}
                        onPress={(index) => this.editLanguage(languageData[index].code)}
                        dataParam={'name'}
                        visible={state.languageVisible}
                        dataSource={state.languageData}
                    /> : null}


                    {/**优惠券*/}
                    {state.advertisementModalVisible && <AdvertisementModal
                        requestClose={() => this.setState({
                            advertisementModalVisible: false,
                        })}
                        userInfo={state.userData}
                        navigator={this.props.navigator}
                        dataSource={state.advertisementModalData}
                        visible={state.advertisementModalVisible}
                    />}


                    {/**推荐*/}
                    {state.recommendAlertVisible ? <AlertDialog
                        contentTv={I18n.t('b.activateText')}
                        leftBtnOnclick={() => {
                            const {navigator} = this.props;
                            const routes = navigator.getCurrentRoutes();
                            const currentRoute = routes[routes.length - 1];
                            if (currentRoute.name !== "BusinessPlanPage") {
                                navigator.push({
                                    component: BusinessPlanPage,
                                    name: 'BusinessPlanPage'
                                })
                            }

                            this.setState({
                                recommendAlertVisible: false,
                            })
                        }}
                        visible={state.recommendAlertVisible}
                        requestClose={() => {
                            this.setState({
                                recommendAlertVisible: false,
                            })
                        }}/> : null}


                    <SearchView
                        {...this.props}
                        updateState={(visible) => {
                            this.setState({visibleSearch: visible})
                        }}
                        visible={this.state.visibleSearch}/>
                    {/**
                     推荐产品 注册包/商务包
                     */}
                    {state.userData && <ProductAdvertising
                        nav={this.props.navigator}
                        requestClose={(productAdvertisingVisible) => {
                            this.setState({
                                productAdvertisingVisible
                            })
                        }}
                        userData={state.userData}
                        visible={state.productAdvertisingVisible}/>}

                </View>

            </SideMenu>
        );
    }

}



